package drds.server.route.sequence;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import drds.server.config.model.DRDS;

/**
 * 使用解析器实现对Sequence处理
 */
public class Sequencer {
	private final SequenceHandler sequenceHandler;

	private final static Pattern pattern = Pattern.compile("(?:(\\s*next\\s+value\\s+for\\s*sequence_(\\w+))(,|\\)|\\s)*)+", Pattern.CASE_INSENSITIVE);

	public Sequencer(int seqHandlerType) {
		switch (seqHandlerType) {
		case DRDS.SEQUENCEHANDLER_MYSQLDB:
			sequenceHandler = SequenceHandlerImpl.getInstance();
			break;
		case DRDS.SEQUENCEHANDLER_REDIS:
			sequenceHandler = SequenceHandlerImpl.getInstance();
			break;
		default:
			throw new java.lang.IllegalArgumentException("Invalid sequnce handler type " + seqHandlerType);
		}
	}

	/**
	 * sequence替换
	 */
	public String getExecuteSql(String sql) {
		String executeSql = null;
		if (null != sql && !"".equals(sql)) {
			// 获取表名。
			Matcher matcher = pattern.matcher(sql);
			if (matcher.find()) {
				String tableName = matcher.group(2);
				long value = sequenceHandler.nextId(tableName);

				// 将MATCHED_FEATURE+表名替换成序列号。
				executeSql = sql.replace(matcher.group(1), " " + value);
			}

		}
		return executeSql;
	}

}
